package com.fzy.common.encode;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 各种格式的编码加码工具类.
 * <p>
 * 集成Commons-Codec,Commons-Lang及JDK提供的编解码方法.
 */
public class EncodeUtil {
    private EncodeUtil(){}

    private static final String DEFAULT_URL_ENCODING = "UTF-8";

    /**
     * utf-8编码, Encode默认为UTF-8.
     */
    public static String encode(String input) {
        return encode(input, DEFAULT_URL_ENCODING);
    }

    /**
     * 编码.
     */
    public static String encode(String input, String encoding) {
        if (null == input || "".equals(input)) {
            return "";
        }
        try {
            return URLEncoder.encode(input, encoding);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Unsupported Encoding Exception", e);
        }
    }

    /**
     * utf-8解码, Encode默认为UTF-8.
     */
    public static String decode(String input) {
        return decode(input, DEFAULT_URL_ENCODING);
    }

    /**
     * URL 解码.
     */
    public static String decode(String input, String encoding) {
        if (null == input || "".equals(input) || "null".equals(input)) {
            return "";
        }
        try {
            return URLDecoder.decode(input, encoding);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Unsupported Encoding Exception", e);
        }
    }


    /**
     * 加密算法
     *
     * @param rawPass
     * @return
     */
    public String encodePassword(String rawPass) {
        return DigestUtils.md5Hex(rawPass);

    }

    /**
     * 判断密码是否一致的算法
     *
     * @param encPass
     * @param rawPass
     * @return
     */
    public boolean isPasswordValid(String encPass, String rawPass) {
        return DigestUtils.md5Hex(rawPass).equals(encPass);
    }

}
